<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 添加分类按钮 -->
      <el-button @click="showAddDialogVisible" type="warning" plain>添加分类</el-button>
      <!-- 商品分类表格渲染 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-row-hover="false"
        show-index
        index-text="#"
        border
      >
        <template slot="isOk" slot-scope="scope">
          <i
            style="color:lightgreen"
            v-if="scope.row.cat_deleted === false"
            class="el-icon-success"
          ></i>
          <i style="color:red" v-else class="el-icon-error"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0" type="success">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="warning">二级</el-tag>
          <el-tag v-else type="danger">三级</el-tag>
        </template>
        <template slot="option" slot-scope="scope">
          <el-button
            @click="editDialog(scope.row)"
            icon="el-icon-edit"
            size="mini"
            type="primary"
            plain
          >编辑</el-button>
          <el-button
            @click="removeCateById(scope.row.cat_id)"
            icon="el-icon-delete"
            size="mini"
            type="danger"
            plain
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog @close="addDialogClosed" title="添加分类" :visible.sync="addDialogVisible" width="50%">
      <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectKeys"
            :options="parentList"
            :props="catProps"
            @change="parentCatChange"
            clearable
            ref="selectRef"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editDialogVisible"
      width="50%"
      :before-close="handleClose"
      @close="editDialogClosed"
    >
      <el-form :rules="editFormRules" ref="editFormRef" :model="editForm" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Category',
  data() {
    return {
      // 商品分类数据请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类数据列表
      cateList: [],
      // 数据总条数
      total: 0,
      // 表格各列的配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'option'
        }
      ],

      // 显示隐藏添加对话框
      addDialogVisible: false,
      // 添加分类数据参数
      addForm: {
        cat_pid: '',
        cat_name: '',
        cat_level: 0
      },
      // 添加分类验证规则
      addFormRules: {
        // 验证分类名称
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      // 父级分类数据,渲染下拉列表
      parentList: [],
      // 下拉列表所选中的父级分类id
      selectKeys: [],
      // 下拉列表的配置项
      catProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
        expandTrigger: 'hover'
      },

      // 显示隐藏编辑分类
      editDialogVisible: false,
      // 编辑分类数据
      editForm: {},
      // 编辑验证规则
      editFormRules: {
        // 验证分类名称
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 监听每页显示的条数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },

    // 监听页码值的改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },

    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('/categories', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res)
      this.cateList = res.data.result
      this.total = res.data.total
    },

    // 显示对话框
    showAddDialogVisible() {
      this.addDialogVisible = true
      // 调用方法,获取父级分类数据,渲染下拉列表
      this.getParentList()
    },
    // 重置添加对话框
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
      // 重置父级分类
      this.selectKeys = []
      // 重置父级分类以及分类等级
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
    },
    //  获取父级分类方法,渲染页面
    async getParentList() {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$messsage.error(res.meta.msg)
      this.parentList = res.data
    },
    // 监听下拉列表的改变的值
    parentCatChange() {
      if (this.selectKeys.length > 0) {
        // 获取父级分类的id,赋值给参数
        this.addForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        // 获取分类名称的等级,赋值给参数
        this.addForm.cat_level = this.selectKeys.length
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    // 实现添加分类功能
    addCate() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/categories', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getCateList()
      })
    },

    // 编辑对话框
    editDialog(catName) {
      this.editForm = catName
      this.editDialogVisible = true
    },
    // 重置编辑对话框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 实现编辑功能
    editCate() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.editForm.cat_id}`, { cat_name: this.editForm.cat_name })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCateList()
        this.editDialogVisible = false
      })
    },

    // 删除分类
    async removeCateById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.error('取消成功')
      const { data: res } = await this.$http.delete(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getCateList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-button {
  margin-bottom: 20px;
}
.el-cascader {
  width: 100%;
}
</style>
